package com.hnnu.shoppingtoghter.demo.controller;

import com.github.pagehelper.PageInfo;
import com.hnnu.shoppingtoghter.demo.config.Constant;
import com.hnnu.shoppingtoghter.demo.entity.Contact;
import com.hnnu.shoppingtoghter.demo.entity.SysUser;
import com.hnnu.shoppingtoghter.demo.service.SysContactService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 联系人详情
 * @Author: 刘艾环
 * @CreateTime： 2022/7/7 2:12
 */
@Slf4j
@Controller
public class ContactController {
    @Autowired
    private SysContactService contactService;

    /**
     * @Description: 显示已设置地址
     * @Author: Liu_aihuan
     * @CreateTime: 2022/7/7 2:50
     * @param: model
     * @param: contact
     * @return: java.lang.String
     **/

    @GetMapping("/my_contact")
    public String index(Model model, Contact contact, HttpSession session){
//        Object userObj = session.getAttribute("user");
//        if (null == userObj){
//            return "redirect:/login";
//        }
        model.addAttribute("contact", contact);
        System.out.println("Contact = "+contact);
        //
        List<Contact> contactList = contactService.selectListByContact(contact);
        System.out.println("contactList = "+ contactList);
        model.addAttribute("contactList", contactList);
        model.addAttribute("num", contactList.size());
        session.setAttribute("length", contactList.size());
        model.addAttribute("num2", Constant.ADDRESS_MAX - contactList.size());

//        int rows = contactService.updateContactIsdefaultpre(contact);
//        if (rows == 0){
//            System.out.println("联系人信息更新失败！");
//            return "my_contact";
//        }
//        int rows2 = contactService.updateContactIsdefaultpre(contact);

        return "my_contact";//
    }

//    @PutMapping("/my_contact/{user_id}")
//    @ResponseBody /* */
//    public String updateIsdefaultPre(@PathVariable("user_id") Long userId){
//        log.info("待更改的联系人列表的userId = {}", userId);
//
//        int rows = contactService.updateContactIsdefaultPre(userId);
//        if (rows > 0){
//            return "success";//
//        }
//        return "error";
//    }

    /**
     * @Description: 修改默认地址
     * @Author: Liu_aihuan
     * @CreateTime: 2022/7/7 12:31
     * @param: contactId
     * @param: session
     * @return: java.lang.String
     **/

    @PutMapping("/my_contact/{id}")
    @ResponseBody /* */
    public String updateIsdefault(@PathVariable("id") Long contactId, HttpSession session) {

        log.info("待更改的联系人列表的Id = {}", contactId);

        int rows = contactService.updateContactIsdefault(((SysUser) session.getAttribute("user")).getId(), contactId);
        if (rows > 0) {
            return "success";//
        }
        return "error";

//        int rows2 = contactService.updateContactIsdefaultPost(contactId);
//        if (rows2 > 0){
//            return "success";//
//        }
//        return "error";
    }

    /**
     * @Description: 插入地址
     * @Author: Liu_aihuan
     * @CreateTime: 2022/7/7 12:32
     * @param: null
     * @return: null
     **/
    @PostMapping("/my_contact")
    public String add(Model model, @Validated Contact contact, BindingResult result, HttpSession session){
        System.out.println("接收到的新增用户信息是: "+contact);
        /** */
        if (result.hasErrors()){
            //
            Map<String, String> errMap = new HashMap<>();
            for (FieldError error : result.getFieldErrors()){
                errMap.put(error.getField(), error.getDefaultMessage());
            }
            model.addAttribute("errors",errMap);
            model.addAttribute("contact", contact);
            return  "my_contact";
        }
//        获取当前登录用户信息，将创建人信息赋给新增的用户对象
          contact.setUserId(((SysUser) session.getAttribute("user")).getId());
//        SysUser loginUser = (SysUser) session.getAttribute("user");
//        user.setCreateUserId(loginUser.getId());
//        user.setCreateUserName(loginUser.getUserName());
//        user.setGmtCreate(new Date());

        log.info("修改后的联系人信息：{}", contact);
        /** 从数据库查询该用户已有地址数 TODO */
        int addressRows = (int) session.getAttribute("length");
        //调用 业务层 将 用户信息 保存至数据库
        if (addressRows >= Constant.ADDRESS_MAX){
            //返回错误信息
            return  "redirect:my_contact";
        }
        int rows = contactService.insertContact(contact);
        if (rows == 0){
            System.out.println("联系人插入信息失败!");
            return "my_contact";
        }
        return "redirect:/my_contact";
    }

    /**
     * @Description: 实现地址修改
     * @Author: Liu_aihuan
     * @CreateTime: 2022/7/7 23:12
     * @param: null
     * @return: null
     **/

    @GetMapping("/my_contact/{id}")
    public String updateIndex(Model model, @PathVariable("id") Long id, HttpSession session){
        Contact contact = contactService.selectContactById(id);
        log.info(" 查找到的联系人信息：{}", contact);
        //
        model.addAttribute("contact",contact);
        session.setAttribute("contact", contact);
        return  "my_contact";
    }

    /**
     * @Description: 修改地址
     * @Author: Liu_aihuan
     * @CreateTime: 2022/7/8 1:15
     * @param: null
     * @return: null
     **/
    @PutMapping("/my_contact")
    public String update(Model model, Contact contact, HttpSession session){

//        Contact sessioncontact = (Contact) session.getAttribute("contact");
//        contact.setId(sessioncontact.getId());
//        contact.setIsdefault(sessioncontact.getIsdefault());
//        contact.setUserRole(sessioncontact.getUserRole());
//        contact.setUserId(sessioncontact.getUserId());

        log.info(" 修改的联系人信息：{}", contact);
        int rows = contactService.updateContact(contact);
        if (rows == 0){
            System.out.println("用户信息更新失败！");
            return "my_contact";
        }
        return "redirect:/my_contact";
    }



    /**
     * @Description: 删除地址
     * @Author: Liu_aihuan
     * @CreateTime: 2022/7/7 23:31
     * @param: null
     * @return: null
     **/
    @DeleteMapping("/my_contact/{id}")
    @ResponseBody /* */
    public String delete(@PathVariable("id") Long contactId){
        log.info("待删除的联系人ID = {}", contactId);

        int rows = contactService.deleteByContactId(contactId);
        if (rows > 0){
            return "success";//
        }
        return "error";
    }









}
